package main

import (
	"context"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx

	// Start the onekeyd service
	err := a.startOneKeyDaemon()
	if err != nil {
		fmt.Printf("Failed to start onekeyd service: %v\n", err)
	}
}

// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
	return fmt.Sprintf("Hello %s, It's show time!", name)
}

// startOneKeyDaemon starts the onekeyd service based on the operating system
func (a *App) startOneKeyDaemon() error {
	// Determine the binary name and directory based on the OS and architecture
	var binaryName string
	var platformDir string

	switch runtime.GOOS {
	case "windows":
		binaryName = "onekeyd.exe"
		switch runtime.GOARCH {
		case "amd64":
			platformDir = "win-x64"
		case "386":
			platformDir = "win-x86"
		default:
			platformDir = "win-" + runtime.GOARCH
		}
	case "darwin": // macOS
		binaryName = "onekeyd"
		switch runtime.GOARCH {
		case "amd64":
			platformDir = "mac-x64"
		case "arm64":
			platformDir = "mac-arm64"
		default:
			platformDir = "mac-" + runtime.GOARCH
		}
	case "linux":
		binaryName = "onekeyd"
		switch runtime.GOARCH {
		case "amd64":
			platformDir = "linux-x64"
		case "arm64":
			platformDir = "linux-arm64"
		case "arm":
			platformDir = "linux-arm"
		default:
			platformDir = "linux-" + runtime.GOARCH
		}
	default:
		return fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
	}

	// Get the current working directory
	wd, err := os.Getwd()
	if err != nil {
		return fmt.Errorf("failed to get working directory: %v", err)
	}

	// Get the path to the binary using working directory
	binaryPath := filepath.Join(wd, "bin", "onekey", platformDir, binaryName)

	// Check if the binary exists
	if _, err := os.Stat(binaryPath); os.IsNotExist(err) {
		return fmt.Errorf("onekeyd binary not found at %s", binaryPath)
	}

	// Start the process
	cmd := exec.Command(binaryPath)

	// Set the working directory to the binary's directory
	cmd.Dir = filepath.Join(wd, "bin", "onekey", platformDir)

	// Start the process
	err = cmd.Start()
	if err != nil {
		return fmt.Errorf("failed to start onekeyd: %v", err)
	}

	fmt.Printf("Started onekeyd service (PID: %d)\n", cmd.Process.Pid)
	return nil
}
